package org.apache.flink.runtime.metrics.groups;

import org.apache.flink.annotation.Internal;
import org.apache.flink.annotation.VisibleForTesting;
import org.apache.flink.api.common.ConsumerID;
import org.apache.flink.metrics.CharacterFilter;
import org.apache.flink.runtime.clusterframework.types.ResourceID;
import org.apache.flink.runtime.metrics.MetricRegistry;
import org.apache.flink.runtime.metrics.dump.QueryScopeInfo;
import org.apache.flink.runtime.metrics.scope.ScopeFormat;
import org.apache.flink.util.Preconditions;

import java.util.HashMap;
import java.util.Map;

/**
 * Special {@link org.apache.flink.metrics.MetricGroup} representing a ResourceProvider.
 *
 * <p>Contains extra logic for adding jobs with tasks, and removing jobs when they do not contain
 * tasks any more
 */
@Internal
public class ResourceProviderMetricGroup extends ComponentMetricGroup<ResourceProviderMetricGroup> {

    private final Map<ConsumerID, ResourceProviderConsumerMetricGroup> consumers = new HashMap<>();

    private final String hostname;

    private final String resoruceProviderId;

    ResourceProviderMetricGroup(MetricRegistry registry, String hostname, String resourceConsumerId) {
        super(
                registry,
                registry.getScopeFormats()
                        .getTaskManagerFormat()
                        .formatScope(hostname, resourceConsumerId),
                null);
        this.hostname = hostname;
        this.resoruceProviderId = resourceConsumerId;
    }

    public static ResourceProviderMetricGroup createResourceProviderMetricGroup(
            MetricRegistry metricRegistry, String hostName, ResourceID resourceID) {
        return new ResourceProviderMetricGroup(metricRegistry, hostName, resourceID.toString());
    }

    public String hostname() {
        return hostname;
    }

    public String taskManagerId() {
        return resoruceProviderId;
    }

    @Override
    protected QueryScopeInfo.ResourceProviderQueryScopeInfo createQueryServiceMetricInfo(
            CharacterFilter filter) {
        return new QueryScopeInfo.ResourceProviderQueryScopeInfo(this.resoruceProviderId);
    }

    // ------------------------------------------------------------------------
    //  consumer groups
    // ------------------------------------------------------------------------

    public ResourceProviderConsumerMetricGroup addConsumer(ConsumerID consumerId, String consumerName) {
        Preconditions.checkNotNull(consumerId);
        String resolvedConsumerName = consumerName == null || consumerName.isEmpty() ? consumerId.toString() : consumerName;
        ResourceProviderConsumerMetricGroup consumerGroup;
        synchronized (this) { // synchronization isn't strictly necessary as of FLINK-24864
            consumerGroup = consumers.get(consumerId);
            if (consumerGroup == null) {
                consumerGroup = new ResourceProviderConsumerMetricGroup(registry, this, consumerId, resolvedConsumerName);
                consumers.put(consumerId, consumerGroup);
            }
        }
        return consumerGroup;
    }

    @VisibleForTesting
    public ResourceProviderConsumerMetricGroup getJobMetricsGroup(ConsumerID consumerId) {
        return consumers.get(consumerId);
    }

    public void removeJobMetricsGroup(ConsumerID jobId) {
        if (jobId != null) {
            ResourceProviderConsumerMetricGroup groupToClose;
            synchronized (this) { // synchronization isn't strictly necessary as of FLINK-24864
                groupToClose = consumers.remove(jobId);
            }
            if (groupToClose != null) {
                groupToClose.close();
            }
        }
    }

    public int numRegisteredJobMetricGroups() {
        return consumers.size();
    }

    // ------------------------------------------------------------------------
    //  Component Metric Group Specifics
    // ------------------------------------------------------------------------

    @Override
    protected void putVariables(Map<String, String> variables) {
        variables.put(ScopeFormat.SCOPE_HOST, hostname);
        variables.put(ScopeFormat.SCOPE_TASKMANAGER_ID, resoruceProviderId);
    }

    @Override
    protected Iterable<? extends ComponentMetricGroup> subComponents() {
        return consumers.values();
    }

    @Override
    protected String getGroupName(CharacterFilter filter) {
        return "taskmanager";
    }
}
